package ans.p112;

import ans.base.TreeNode;

import java.util.LinkedList;
import java.util.List;

/**
 * #      112
 * 名称   路径总和
 * 链接   https://leetcode-cn.com/problems/path-sum
 * 题解   [1237](https://leetcode-cn.com/problems/path-sum/solution)
 * 通过率 52.0%
 * 难道   简单
 */

public class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        return !pathSum(root, targetSum).isEmpty();
    }

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> ans = new LinkedList<>();
        LinkedList<Integer> integers = new LinkedList<>();
        if (root != null) {
            integers.add(root.val);
            traceback(ans, integers, root, targetSum, root.val);
            integers.remove(integers.size() - 1);
        }
        return ans;
    }

    private void traceback(List<List<Integer>> ans, List<Integer> list, TreeNode node, int targetSum, int sum) {
        if (node.left == null && node.right == null && sum == targetSum) {
            ans.add(new LinkedList<>(list));
            return;
        }
        if (node.left != null) {
            list.add(node.left.val);
            traceback(ans, list, node.left, targetSum, sum + node.left.val);
            list.remove(list.size() - 1);
        }
        if (node.right != null) {
            list.add(node.right.val);
            traceback(ans, list, node.right, targetSum, sum + node.right.val);
            list.remove(list.size() - 1);
        }
    }
}